Repository navigation
fix(command): 流截断不再冷却账号 / keep accounts routable on a truncated stream - #637
BrianBoyCN wants to merge 3 commits into
Conversation
A Command Code stream that the upstream cut after delivering content was classified as a generic `unavailable` error, which applies a 15s cooldown that `nextBackoffCooldown` lifts to the 30s floor on repeat failures. On a single-account route that turns one truncated answer into a burst of "all accounts are cooling down" failures, and the client reads them as rate limiting rather than as a retryable upstream cut. Report the cut with a distinct `upstream_stream_truncated` code and, following the `upstream_empty` precedent, keep the account routable (failover, cooldown 0, retry-after 0). Also carry the observed stream shape in the message so a cut answer can be told apart from an upstream that aborted before producing anything; no prompt or completion text is included. Gated behind: - go test ./... / -race on command+executor / go vet ./... / gofmt - scripts/release-notes.py validate
caigee-cmd
left a comment
There was a problem hiding this comment.
感谢 @BrianBoyCN 这么细致的排查,线上数据和根因分析都很清楚,upstream_empty 同款的豁免思路我也认同,方向没问题 👍
合并前有几处小问题想麻烦再调整一下:
-
bytesRead从来没有被累加(internal/providers/command/wire.go)。streamStats.bytesRead只在声明和describe()里出现,streamEventsObserved没有给它加过值,所以错误信息里永远是0 bytes。PR 描述里的122605 bytes来自request_stream_diagnostics,不是这段代码产出的。建议在readLine之后stats.bytesRead += len(line)(顺便加一条断言 bytes 非 0 的测试)。 -
(*streamStats).observe没被调用。streamEventsObserved里把同样的逻辑内联写了一遍,留了一份死代码。直接在循环里调stats.observe(event)就好。 -
TestChatNonStreamTruncationReportsObservedShape的"不回显内容"断言是空断言。这个测试的流内容是"Hel",却检查 message 里不含"partial",无论实现如何都会通过。建议改成检查不含"Hel"(或者把文本换成一个更独特的字符串)。 -
TestClassifyErrorUpstreamEmptyNoCooldown上的两行注释被删了,和本 PR 无关,麻烦恢复一下。 -
(可讨论,不阻塞)
newStreamTruncatedError目前对所有"没有终态事件"的流都生效,包括一个事件都没收到就断开的情况;但常量注释和 changelog 写的是"delivered content and then ended"。要么在注释/changelog 里把范围说成"任何未见终态的流",要么只在contentSeen为 true 时才打这个 code,二选一保持一致即可。
我检查了兼容性:只影响 Command Code 这一种失败的冷却和对外 error code(从兜底的 upstream_error 变成 upstream_stream_truncated),没有改通用 unavailable 冷却和 backoffFloor,也没有 schema 或公开接口改动,不算破坏性改动。
abort / pause_turn 那两点也很有价值,欢迎单独开 issue。改完我再看一下就合,辛苦了!
caigee-cmd
left a comment
There was a problem hiding this comment.
这个 PR 在 2026-12-03 13:30(上海时间)的审查意见之后,只合了几次 main,本身的代码提交还是 03554f20,上次提的问题都还在:
internal/providers/command/wire.go:streamStats.bytesRead仍然只在声明和describe()里出现,没有累加,错误信息里的字节数永远是 0。(*streamStats).observe仍然没有被调用,streamEventsObserved里把同样的逻辑内联写了一遍,是死代码。TestChatNonStreamTruncationReportsObservedShape的流内容是"Hel",却断言 message 不含"partial",仍然是空断言。TestClassifyErrorUpstreamEmptyNoCooldown上和本 PR 无关的两行注释仍然被删了。- (可讨论)常量注释和 changelog 写的是“已下发内容后被切断”,但
newStreamTruncatedError对所有没有终态事件的流都生效,包括一个事件都没收到就断开的情况,两边还没对齐。
方向没问题,上面 1–4 改完我再看。
- wire.go: count raw bytes via a counting reader so streamStats.bytesRead is actually accumulated (was always 0); call stats.observe() instead of the duplicated inline logic; drop the unused streamEvents wrapper. - chat_test.go: make the no-content-echo assertion real (check for the actual streamed fragment) and assert bytesRead is non-zero. - classify_test.go: restore the two comment lines above TestClassifyErrorUpstreamEmptyNoCooldown that were unrelated to this change. - Align the code's actual scope (any stream without a terminal event, content or not) across tlserr.go, errors.go, and the changelog. - executor/error.go: correct the cooldown-floor comment — nextBackoffCooldown's 30s floor applies from the third consecutive same-kind failure, not to any positive cooldown.
4b2d814 to
294edff
Compare
|
感谢再列一遍,5 条都已处理(e2ea1ae9):
另外把 executor/error.go 里「任何正数冷却都会被抬到 30s」的注释修准了:30s 地板实际从第 3 次同 kind 连续失败才生效(前两次 15s),线上那串次级失败 15s 就足以复现。 本地已过 go test ./... / -race / vet / gofmt / release-notes.py validate,并合入了 main(v0.8.6 changelog archive)。CI 在跑,麻烦再看一下 🙏 |
caigee-cmd
left a comment
There was a problem hiding this comment.
昨天提的 5 点都改到了:countingReader 已接上,bytesRead 会累加,循环改走 observe,测试也会拦住 0 bytes 和内容回显。措辞按「未见终态事件就不上冷却」对齐,说得通。CI 全绿,可以合。
中文
问题现象
单账号 Command Code 路由上,长请求会周期性整体不可用。实测(2026-12-03,一个账号、1336 成功请求)当天 47 次失败里有 35 次是
all accounts are cooling down,而真正的截断只有 9 次——一次截断放大成约 4 次次级失败:这 35 条次级失败的
error_kind/error_code都是rate_limit,客户端会按限流退避,而实际原因是「上游把答到一半的流切断了」——完全可重试,且与账号健康无关。根因
/alpha/generate是 NDJSON 流,终态事件是finish-step/finish。适配层(internal/providers/command/rewrite.go的sseWriter.finish()与chat.go的aggregateResponse())在没见到终态时构造的是一个普通unavailable错误:Classify()落到 default 分支 →Cooldown = 15s。而nextBackoffCooldown有 30s 地板:于是任何正数冷却都会被抬到 ≥30s,同类失败再指数退避。单账号路由上没有别的账号可以 failover,整个渠道被冻结。这与
internal/executor/error.go里既有的传输层失败处理(Failover:false, Cooldown:0,理由正是「单账号路由下一次握手超时就会变成 all accounts are cooling down」)自相矛盾:「上游已收下请求、已经产出内容、中途被切断」比握手失败更说明账号是健康的,却反而被惩罚。线上证据(
request_stream_diagnostics):两次有诊断的截断分别是upstream_status=200、sse_event_count=532 / bytes=122605和sse_event_count=19 / bytes=3713,saw_done=0、cancellation_source=upstream_stream_error。即上游正常建流、正常下发内容,然后在没有任何终态帧的情况下关闭。9 次截断的耗时全部 ≥37s,而当天成功请求 p90 是 37.3s —— 只有长尾请求会被切断。修复
1. 给截断一个独立 code,并按
upstream_empty的先例豁免冷却internal/providers/command/errors.go新增newStreamTruncatedError,把截断从"通用 unavailable"里分出来,带providers.CodeStreamTruncated。internal/executor/error.go紧随既有的upstream_empty特例处理它:Failover保持 true(多账号时仍换账号),Cooldown为 0 让账号立即回到轮询池。这与 #288(upstream_empty不冷却账号)是同一套模式、同一处代码,不新增策略分支。2. 报错信息带上实际观测到的流形态
原来只有一句固定文案,无法区分「答到一半被切」和「上游什么都没产出就中断」。
wire.go里新增streamStats(事件数、字节数、最后一个事件类型、是否出现过真实内容),随截断错误一起带出,例如:新增的诊断会写进请求日志,让下一次故障可以自证,而不是靠猜。不包含任何提示词或生成内容,只含计数与事件类型名。
测试
TestClassifyErrorStreamTruncatedNoCooldown— 截断 →Kind=unavailable、Failover=true、Cooldown=0、RetryAfter=0TestStreamTruncationDoesNotCoolPool— 端到端:对唯一账号观测到截断后,DownUntil仍为空、ModelDownUntil为空、RetryAfter为 0,即下一次 pick 能成功TestStreamReadErrorPreservesTruncatedCode— 网关StreamReadError包装后 code 不丢(否则冷却会回归)TestChatStreamTruncationSurfacesCode— 流式路径:部分内容已上线,pipe 错误仍带upstream_stream_truncatedTestChatNonStreamTruncationReportsObservedShape— 非流式路径的观测形态与「不回显内容」断言TestClassifyErrorUpstreamEmptyNoCooldown对照组(普通 unavailable 保留冷却)未改动,确认只有这两个特例被豁免go test ./...、go test -race ./internal/providers/command/ ./internal/executor/、go vet ./...、gofmt、git diff --check、scripts/release-notes.py validate全部通过。范围与未做的事
unavailable的 15s 冷却,也没有动backoffFloor。只对这一个 code 豁免。实测中发现、未包含在本 PR 的两处
{"type":"abort"}事件被忽略。 官方command-codeCLI(我反编译 1.93.4 / 1.94.0 的dist/cli.mjs核对)对abort是显式终态,抛AbortError;而适配层handle()的default: return nil会吞掉它,于是「上游主动 abort」被误报成「流被截断」。02:18 那条只出 19 个事件就断的,很可能就是这种情况。要不要把abort单列成一个 finish_reason,需要先定语义。pause_turn被当成功。 官方 CLI 见到pause_turn会带 continuation 重发(最多 5 次);适配层normalizeFinishReason把它归成stop,等于把「这一轮没跑完」静默当正常结束。修它需要引入续接逻辑,属于新功能而非 bugfix。这两点建议单独开 issue 讨论,需要的话我可以接着提。
English
Problem
On a single-account Command Code route the whole channel periodically went unavailable. Measured on 2026-12-03 (one account, 1336 successful requests): 35 of the day's 47 failures were
all accounts are cooling down, while only 9 were actual stream truncations — roughly a 4x amplification from one cut stream.All 35 secondary failures logged
error_kind/error_code = rate_limit, so clients back off as if throttled, when the actual cause — the upstream cutting a half-delivered stream — is retryable and says nothing about account health.Root cause
/alpha/generateis an NDJSON stream whose terminal events arefinish-step/finish. When no terminal event arrives, the adapter (sseWriter.finish()ininternal/providers/command/rewrite.goandaggregateResponse()inchat.go) builds a genericunavailableerror:Classify()falls to its default branch →Cooldown = 15s. AndnextBackoffCooldownhas a 30s floor:So any positive cooldown is lifted to ≥30s, with exponential backoff on repeats. With no second account to fail over to, the entire channel freezes. This contradicts the transport-failure handling already in
internal/executor/error.go(Failover:false, Cooldown:0, whose comment is literally that a single handshake timeout turns into "all accounts are cooling down" for every following request): a stream the upstream accepted, started serving, and then cut is more evidence the account is healthy than a failed handshake, yet it was the one being punished.Wire evidence (
request_stream_diagnostics): the two truncations with diagnostics showedupstream_status=200withsse_event_count=532 / bytes=122605andsse_event_count=19 / bytes=3713,saw_done=0,cancellation_source=upstream_stream_error. The upstream opened the stream, delivered content, then closed without any terminal frame. All nine truncations took ≥37s against a same-day p90 of 37.3s — only long-tail requests get cut.Fix
1. Give the cut its own code and exempt it from cooldown, following the
upstream_emptyprecedent.newStreamTruncatedErrorininternal/providers/command/errors.gomarks the cut withproviders.CodeStreamTruncated;internal/executor/error.gohandles it next to the existingupstream_emptycase:Failoverstays true (multi-account routes still move on),Cooldown0 returns the account to the rotation immediately. Same pattern, same place as #288 — no new policy branch.2. Report the observed stream shape. The old message was a constant, so a cut answer could not be told apart from an upstream that aborted before producing anything.
streamStatsinwire.gorecords event count, bytes, last event type, and whether real content arrived:It lands in the request log so the next incident explains itself. No prompt or completion text is included — counters and event type names only.
Tests
TestClassifyErrorStreamTruncatedNoCooldown—Kind=unavailable,Failover=true,Cooldown=0,RetryAfter=0TestStreamTruncationDoesNotCoolPool— end to end on the only account:DownUntilstays zero,ModelDownUntilempty,RetryAfter0, so the next pick succeedsTestStreamReadErrorPreservesTruncatedCode— the code survives the gateway'sStreamReadErrorwrapper (otherwise the cooldown regresses)TestChatStreamTruncationSurfacesCode— streaming path: partial content is on the wire and the pipe error still carriesupstream_stream_truncatedTestChatNonStreamTruncationReportsObservedShape— observed shape plus "does not echo streamed content"TestClassifyErrorUpstreamEmptyNoCooldowncontrol case (generic unavailable keeps its cooldown) is untouched, proving only these two codes are exemptedgo test ./...,go test -race ./internal/providers/command/ ./internal/executor/,go vet ./...,gofmt,git diff --check, andscripts/release-notes.py validateall pass.Scope
unavailablekeeps its 15s cooldown;backoffFlooris untouched. Only this one code is exempted.Found while measuring, not in this PR
{"type":"abort"}is ignored. The officialcommand-codeCLI (I decompileddist/cli.mjsfor 1.93.4 and 1.94.0) treatsabortas an explicit terminal (AbortError); the adapter'sdefault: return nilswallows it, so an upstream-initiated abort is misreported as a truncation. The 02:18 request that ended after 19 events is likely this case. Givingabortits own finish_reason needs a semantic decision first.pause_turnis reported as success. The official CLI re-sends with a continuation (up to 5 attempts);normalizeFinishReasonmaps it tostop, silently treating an unfinished turn as complete. Fixing it means adding continuation logic — a feature, not a bugfix.Both deserve their own issue; happy to file them.